package com.ken.elmboot.interceptor;

import com.ken.elmboot.bean.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ken
 */
public class LoginInsterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 统一拦截（查询当前session是否存在admin）(这里admin会在每次登陆成功后，写入session)
            Admin admin = (Admin) request.getSession().getAttribute("login_user");
            if(admin != null) {
                return true;// 如果设置为true时，请求将会继续执行后面的操作
            }
            response.sendRedirect(request.getContextPath()+"/login.html");
        }catch (IOException e) {
            e.printStackTrace();
        }
        return false;// 如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
